<template>
  <a-tree-select
    v-bind="args ? { ...args } : null"
    :data="sectionTree.data"
    :placeholder="placeholder"
    :allow-search="isSearch"
    :disabled="disabled"
    :field-names="{ key: 'id', title: 'name', children: 'children' }"
    @change="(e) => changeSection(e as number)"
  ></a-tree-select>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { GetOrganizationchart } from '@/api/home/System settings/organizational-structure/index';

  interface TsectionData {
    id: number;
    pid: number;
    name: string;
    children?: TsectionData[];
  }
  const props = withDefaults(
    // 参数说明
    defineProps<{
      placeholder?: string;
      isSearch?: boolean; // 是否启用搜索
      disabled?: boolean;
      args?: any; // 对象，放置a-table的剩余属性
    }>(),
    {
      isSearch: false,
      disabled: false
    }
  );

  const emit = defineEmits(['selectSection']);
  const sectionTree = reactive<{ data: TsectionData[] }>({ data: [] });
  const changeSection = (e: number) => {
    emit('selectSection', e);
  };
  const changeSectionDataFn: any = (section: TsectionData[], pid = 0) => {
    const tree: any = [];
    for (const item of section) {
      if (item.pid === pid) {
        const children = changeSectionDataFn(section, item.id);
        if (children.length) {
          item.children = children;
        }
        tree.push(item);
      }
    }
    return tree;
  };
  const init = async () => {
    const res = await GetOrganizationchart();
    sectionTree.data = changeSectionDataFn(res.department as TsectionData[]);
  };
  init();
</script>

<style lang=""></style>
